/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wh.server;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import wh.Player;

/**
 *
 * @author Dave
 */
public class ServerHelper extends Thread {
    static HashMap<Integer, Method> functions;
    static int max = 0;
    int numOfPlayers = 0;
    ArrayList<Player> list;
    final Object lock = new Object();
    public final static int SLEEP = 50;

    //No one should be allowed to create a basic ServerHelper
    protected ServerHelper(HashMap<Integer, Method> funct, int maxPlayer) {
        functions = funct;
        max = maxPlayer;
        list = new ArrayList<Player>(maxPlayer);
    }

    public int addPlayer(Player s) {
	System.out.println("Adding player");
        synchronized(lock) {
            if (numOfPlayers < max) {
                list.add(s);
                numOfPlayers++;
            } else {
                return 0;
            }
            return numOfPlayers;
        }
    }

    public int removePlayer(int index) throws ArrayIndexOutOfBoundsException {
        synchronized(lock) {
            if (index < numOfPlayers) {
                if(list.remove(index) != null) {
                    numOfPlayers--;
                    return 1;
                }
                return 0;
            } else {
                throw new ArrayIndexOutOfBoundsException("Cannot remove socket");
            }
        }
    }

    public int removePlayer(Player p) {
        synchronized(lock) {
            if(list.remove(p)) {
                numOfPlayers--;
                return 1;
            }
            return 0;
        }
    }
}
